<template>
  <div class="update-name">
    <!-- 导航栏 -->
    <van-nav-bar
      title="修改昵称"
      left-text="取消"
      right-text="完成"
      @click-left="$emit('close')"
      @click-right="onConfirm"
    />

    <div class="name-field-wrap">
      <van-field
      v-model="localName"
      rows="2"
      autosize
      type="textarea"
      maxlength="7"
      show-word-limit
    />
    </div>
  </div>
</template>

<script>
import { updateUserProfile } from '@/api/user'
export default {
  name: 'UpdateName',
  components: {},

  props: {
    // 声明接受父组件 v-model 传递的 value 数据
    value: {
      type: String,
      required: true
    }
  },

  data () {
    return {
      localName: this.value
    }
  },

  computed: {},

  watch: {},

  created () {},

  mounted () {},

  methods: {
    async onConfirm () {
      this.$toast.loading({
        message: '保存中',
        forbidClick: true
      })
      try {
        // 请求提交更新用户昵称
        await updateUserProfile({
          name: this.localName
        })

        this.$toast.success('保存成功')
        // 更新成功 -> 修改父组件的 name -> 关闭弹出层
        // 发布 input 事件，更新父组件 v-model 绑定的数据
        this.$emit('input', this.localName)
        this.$emit('close')
      } catch (error) {
        if (error && error.response && error.response.status === 409) {
          this.$toast.fail('昵称已存在')
        }
      }
      // console.log('onConfirm')
    }
  }
}
</script>
<style lang="less" scoped>
.name-field-wrap {
  padding: 10px;
}
</style>
